/**
 * 表单验证工具函数
 */

// 邮箱验证
export const validateEmail = (email: string): boolean => {
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailReg.test(email)
}

// 手机号验证
export const validatePhone = (phone: string): boolean => {
  const phoneReg = /^1[3-9]\d{9}$/
  return phoneReg.test(phone)
}

// 身份证验证
export const validateIdCard = (idCard: string): boolean => {
  const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return idCardReg.test(idCard)
}

// 密码强度验证（至少8位，包含字母和数字）
export const validatePassword = (password: string): boolean => {
  const passwordReg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$/
  return passwordReg.test(password)
}

// 用户名验证（2-20位字母数字下划线）
export const validateUsername = (username: string): boolean => {
  const usernameReg = /^[a-zA-Z0-9_]{2,20}$/
  return usernameReg.test(username)
}

// URL验证
export const validateUrl = (url: string): boolean => {
  const urlReg = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/
  return urlReg.test(url)
}

// 数字验证
export const validateNumber = (value: string): boolean => {
  const numberReg = /^[0-9]+$/
  return numberReg.test(value)
}

// 小数验证
export const validateDecimal = (value: string): boolean => {
  const decimalReg = /^[0-9]+(\.[0-9]+)?$/
  return decimalReg.test(value)
}

// 中文验证
export const validateChinese = (value: string): boolean => {
  const chineseReg = /^[\u4e00-\u9fa5]+$/
  return chineseReg.test(value)
}

// 英文验证
export const validateEnglish = (value: string): boolean => {
  const englishReg = /^[a-zA-Z]+$/
  return englishReg.test(value)
}

// 日期格式验证 (YYYY-MM-DD)
export const validateDate = (date: string): boolean => {
  const dateReg = /^\d{4}-\d{2}-\d{2}$/
  return dateReg.test(date)
}

// 时间格式验证 (HH:MM:SS)
export const validateTime = (time: string): boolean => {
  const timeReg = /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/
  return timeReg.test(time)
}

// IP地址验证
export const validateIP = (ip: string): boolean => {
  const ipReg = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
  return ipReg.test(ip)
}

// 端口号验证
export const validatePort = (port: string): boolean => {
  const portNum = parseInt(port)
  return portNum >= 1 && portNum <= 65535
}

// 必填验证
export const validateRequired = (value: any): boolean => {
  if (value === null || value === undefined) {
    return false
  }
  if (typeof value === 'string') {
    return value.trim().length > 0
  }
  if (Array.isArray(value)) {
    return value.length > 0
  }
  return true
}

// 长度验证
export const validateLength = (value: string, min: number, max: number): boolean => {
  const length = value.length
  return length >= min && length <= max
}

// 范围验证
export const validateRange = (value: number, min: number, max: number): boolean => {
  return value >= min && value <= max
}

// 文件类型验证
export const validateFileType = (file: File, allowedTypes: string[]): boolean => {
  return allowedTypes.indexOf(file.type) !== -1
}

// 文件大小验证 (单位：MB)
export const validateFileSize = (file: File, maxSize: number): boolean => {
  const fileSizeMB = file.size / 1024 / 1024
  return fileSizeMB <= maxSize
}

// 表单验证规则生成器
export const createValidationRules = () => {
  return {
    required: (message: string = '此项为必填项') => ({
      required: true,
      message,
      trigger: 'blur'
    }),
    
    email: (message: string = '请输入正确的邮箱格式') => ({
      validator: (_: any, value: string, callback: Function) => {
        if (!value || validateEmail(value)) {
          callback()
        } else {
          callback(new Error(message))
        }
      },
      trigger: 'blur'
    }),
    
    phone: (message: string = '请输入正确的手机号格式') => ({
      validator: (_: any, value: string, callback: Function) => {
        if (!value || validatePhone(value)) {
          callback()
        } else {
          callback(new Error(message))
        }
      },
      trigger: 'blur'
    }),
    
    password: (message: string = '密码至少8位，包含字母和数字') => ({
      validator: (_: any, value: string, callback: Function) => {
        if (!value || validatePassword(value)) {
          callback()
        } else {
          callback(new Error(message))
        }
      },
      trigger: 'blur'
    }),
    
    length: (min: number, max: number, message?: string) => ({
      min,
      max,
      message: message || `长度在 ${min} 到 ${max} 个字符`,
      trigger: 'blur'
    })
  }
} 